package cn.gotom.core.web.action;

import java.util.HashSet;
import java.util.List;

import org.apache.log4j.Logger;

import cn.gotom.coding.EncodingUtils;
import cn.gotom.core.pojos.Role;
import cn.gotom.core.pojos.User;
import cn.gotom.core.service.RoleService;
import cn.gotom.core.service.UserService;
import cn.gotom.core.web.Constants;

import com.google.inject.Inject;

public class UserRoleAction implements MenuInf
{
	protected final Logger log = Logger.getLogger(getClass());

	public String remove()
	{
		log.debug("remove id=" + user.getId());
		user = userService.get(user.getId());
		if (user != null)
		{
			roleService.remove(user);
		}
		return Constants.LIST;
	}

	public String save()
	{
		user.setRoles(new HashSet<Role>());
		roleList = roleService.findAll();
		if (ids != null)
		{
			for (String roleId : ids)
			{
				for (Role role : roleList)
				{
					if (role.getId().equals(roleId))
					{
						user.getRoles().add(role);
						break;
					}
				}
			}
		}
		EncodingUtils.encoding(user, "GBK", "cp850");
		user = userService.save(user);
		return Constants.LIST;
	}

	public String list()
	{
		roleList = roleService.findAll();
		userList = userService.findAll();
		if (user != null)
		{
			user = userService.get(user.getId());
			if (user != null && user.getRoles() != null)
			{
				for (Role role : roleList)
				{
					role.setChecked(user.getRoles().contains(role));
				}
			}
		}
		else
		{
			user = new User();
		}
		for (User r : userList)
		{
			EncodingUtils.encoding(r, "cp850", "GBK");
		}
		for (Role r : roleList)
		{
			EncodingUtils.encoding(r, "cp850", "GBK");
		}
		return Constants.SUCCESS;
	}

	public String input()
	{
		user = null;
		return list();
	}

	@Inject
	private UserService userService;

	@Inject
	private RoleService roleService;

	private User user;

	private String[] ids;

	private List<Role> roleList;

	private List<User> userList;

	@Override
	public String getName()
	{
		return "用户管理";
	}

	@Override
	public String getGroupName()
	{
		return "系统管理";
	}

	@Override
	public int getMenuSort()
	{
		return 10000;
	}

	public User getUser()
	{
		return user;
	}

	public void setUser(User user)
	{
		this.user = user;
	}

	public List<Role> getRoleList()
	{
		return roleList;
	}

	public void setRoleList(List<Role> roleList)
	{
		this.roleList = roleList;
	}

	public List<User> getUserList()
	{
		return userList;
	}

	public void setUserList(List<User> userList)
	{
		this.userList = userList;
	}

	public String[] getIds()
	{
		return ids;
	}

	public void setIds(String[] ids)
	{
		this.ids = ids;
	}

}
